package top.lixunda.common.validate.validate;

import top.lixunda.common.validate.annotation.XumEmail;
import top.lixunda.common.validate.core.ValidateError;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.regex.Pattern;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 */
public class EmailValidate implements AnnotationValidate {

    private static final String EMAIL_REGEX = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\\\.][A-Za-z]{2,3}([\\\\.][A-Za-z]{2})?$";

    @Override
    public boolean support(Class annotationClass) {
        return XumEmail.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        XumEmail a = (XumEmail) annotation;
        boolean isNull = (value == null || (value instanceof String && "".equals(value)));
        if (isNull) {
            return null;
        }
        return Pattern.matches(EMAIL_REGEX, value.toString()) ? null :
                new ValidateError(getErrorMessage(a.message(), field, value));
    }

    private String getErrorMessage(String message, Field field, Object value) {
        return "".equals(message)
                ? field.getName() + "不是一个合法的邮箱地址"
                : message.replaceAll("#value#", String.valueOf(value)).replaceAll("#name#", field.getName());
    }

}
